package com.etlmaster.executor.steps.control;

import java.util.List;

import com.etlmaster.executor.utils.StepState;
import com.etlmaster.jdbc.JdbcTemplate;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class AssignSqlProcessor extends AssignProcessor{

	@Override
	public int process(AssignStepMeta meta) {
		if(expression.indexOf(" in ")>0){
			int posi = expression.indexOf(" in ");
	    	String variableName = expression.substring(0,posi);
	    	String sqlStatement = expression.substring(posi+4,expression.length());
	    	JdbcTemplate jt = new JdbcTemplate(meta.getDsName());
	    	String sql = meta.variableSubstitution(sqlStatement);
	    	List list = jt.queryForList(sql);
	    	if(list!=null && list.size()>0){
	    		if("sql".equalsIgnoreCase(meta.getParatype())){
		    		meta.getStepState().getReturnValue().put(variableName.trim(), list.get(0));
		    	}else{
		    		meta.getStepState().getReturnValue().put(variableName.trim(), list);
		    	}
	    	}else{
	    		//如果sql语句错误也需要返回值，否则后续步骤回错误
	    		meta.getStepState().getReturnValue().put(variableName, list);
	    		meta.log("WARN","SQL语句查询出错或则查询结果为空，{}",sql);
	    	}

		}else{
			meta.log("ERROR","SQL赋值未设置变量名，{}",expression);
			return StepState.RUNNING_FAILED;
		}
		return StepState.RUNNING_SUCCESSED;
	}
	
}
